package com.dark.interceptor;

import com.dark.base.FlowerFallingException;
import com.dark.controller.user.UserController;
import com.dark.model.po.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * ClassName: LoginInterceptor
 * Description:LoginInterceptor
 *
 * @author chengluchao
 * @date: 2023/6/1 9:20 AM
 * @since 1.4.25
 */
@Component
@Slf4j
public class LoginInterceptor extends HandlerInterceptorAdapter implements CommandLineRunner {

    @Resource
    UserController userController;

    @Override
    public void run(String... args) throws Exception {

    }

    @Value("${flower-falling.use.uri.whitelist:true}")
    private boolean useWhitelist;

    @Value("${flower-falling.login.url://127.0.0.1:9901/html/login.html}")
    private String loginUrl;



    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (useWhitelist && "/".equals(request.getRequestURI())) {
            return true;
        }

        try {
            User user = userController.getUserInfo();
            return true;
        } catch (FlowerFallingException jingException) {
            safetyWriteResponse(response, 301, "Not login", loginUrl);
            return false;
        }

    }

    private void safetyWriteResponse(HttpServletResponse response, int status, String body, String location) throws IOException {
        if (!response.isCommitted()) {
            response.setStatus(status);
            if (!StringUtils.isEmpty(location)) {
                response.setHeader("Location", location);
            }
            response.getWriter().print(body);
            response.flushBuffer();
        }
    }

}
